<template>
  <div class="app-container">
    <el-col>
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <el-tree
            :data="categories"
            :props="defaultProps"
            node-key="id"
            default-expand-all
            :expand-on-click-node="false"
            style="width:60%"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="20">
        <div class="grid-content bg-purple-light">
          <el-button type="primary" @click="add">
            <i class="el-icon-upload el-icon-plus" />
            新增
          </el-button>
          <el-table :data="contents" style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="内容标题">
                    <span>{{ props.row.title }}</span>
                  </el-form-item>
                  <el-form-item label="子标题">
                    <span>{{ props.row.subTitle }}</span>
                  </el-form-item>
                  <el-form-item label="跳转链接">
                    <a :href="props.row.url" target="view_window">点击跳转</a>
                  </el-form-item>
                  <el-form-item label="内容">
                    <span>{{ props.row.content }}</span>
                  </el-form-item>
                  <el-form-item label="创建时间">
                    <span>{{ props.row.created }}</span>
                  </el-form-item>
                  <el-form-item label="更新时间">
                    <span>{{ props.row.updated }}</span>
                  </el-form-item>
                  <el-form-item label="图片">
                    <img :src="props.row.pic" class="ContentimgSize">
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="内容 ID" prop="id" />
            <el-table-column label="内容标题" prop="title" />
            <el-table-column label="标题描述" prop="titleDesc" />
            <el-table-column fixed="right" label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleClick(scope.row)">编辑</el-button>
                <el-button type="text" size="small" @click="deleteClick(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-dialog title="编辑内容" :visible.sync="dialogVisible" width="80%" top="0px">
            <el-form ref="form" :model="content" label-width="80px">
              <el-form-item label="内容标题">
                <el-input v-model="content.title" />
              </el-form-item>
              <el-form-item label="小标题">
                <el-input v-model="content.subTitle" />
              </el-form-item>
              <el-form-item label="描述">
                <el-input v-model="content.titleDesc" />
              </el-form-item>
              <el-form-item label="跳转链接">
                <el-input v-model="content.url" />
              </el-form-item>
              <el-form-item label="内容">
                <el-input v-model="content.content" type="textarea" />
              </el-form-item>
              <el-form-item label="商品图片">
                <el-upload
                  class="avatar-uploader"
                  action="/api/file/upload/item"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="content.pic" :src="content.pic" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="onSubmit">保存</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </div>
        <!-- 分页 -->
        <div class="block">
          <el-pagination
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-col>
    </el-col>
  </div>
</template>

<script>
import {
  fetchContentCategories,
  fetchContent,
  deleteContent,
  addContent,
  updateContent
} from '@/api/cms'
import { node } from 'clipboard'
export default {
  name: 'Content',
  data() {
    return {
      categories: [],
      defaultProps: {
        children: 'children',
        label: 'label',
        isLeaf: 'isLeaf'
      },
      // 总条数
      total: 0,
      limit: 10,
      // 当前页
      currentPage: 1,
      contents: [], // 内容列表数据
      content: {
        id: '',
        title: '',
        categoryId: '',
        subTitle: '',
        titleDesc: '',
        url: '',
        content: '',
        pic: ''
      }, // 当前内容
      dialogVisible: false, // 客户编辑弹框的标识
      node: '' // 当前所在节点
    }
  },
  created: function() {
    this.getData()
  },
  methods: {
    // 上传图片成功
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.content.pic = res.data
    },
    // 上传前校验
    beforeAvatarUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
      }
      return isLt10M
    },
    add() {
      // 判断当前所在节点是否为叶子节点
      if (this.node.isLeaf == true) {
        this.dialogVisible = true
        this.content = {
          id: '',
          title: '',
          categoryId: this.node.id,
          subTitle: '',
          titleDesc: '',
          url: '',
          content: '',
          pic: ''
        }
      } else {
        this.$message({
          type: 'warning',
          message: '必须进入叶子节点才能进行操作! '
        })
      }
    },
    onSubmit() {
      this.$confirm('是否确认操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.content.id != '') {
            updateContent(this.content).then(res => {
              this.$message({
                type: 'success',
                message: '更新成功'
              })
              // 关闭弹出层
              this.dialogVisible = false
              // 刷新
              this.fetchData(this.node)
            })
          } else {
            addContent(this.content).then(res => {
              this.$message({
                type: 'success',
                message: '内容新增成功'
              })
              // 关闭弹出层
              this.dialogVisible = false
              // 刷新
              this.fetchData(this.node)
            })
          }
        })
        .catch(() => {
          // this.$message({
          //   type: "info",
          //   message: "已取消操作"
          // });
        })
    },
    // 获取分类数据
    getData() {
      fetchContentCategories().then(res => {
        this.categories = res.data
      })
    },
    // 获取最新内容数据
    fetchData(node) {
      fetchContent(node.id).then(res => {
        this.total = res.data.total
        this.contents = res.data.data
      })
    },
    // 节点点击事件
    handleNodeClick(node) {
      this.node = node
      this.content.categoryId = node.id
      // 如果被点击的是叶子节点，加载数据
      if (node.isLeaf == true) {
        this.fetchData(this.node)
      } else {
        // 否则清空数据
        this.contents = []
        this.node = ''
        this.total = 0
        this.currentPage = 1
        this.limit = 10
      }
    },
    // 编辑
    handleClick(row) {
      console.log(row)
      this.dialogVisible = true
      this.content = {
        id: row.id,
        title: row.title,
        categoryId: this.node.id,
        subTitle: row.subTitle,
        titleDesc: row.titleDesc,
        url: row.url,
        content: row.content,
        pic: row.pic
      }
    },
    // 删除
    deleteClick(row) {
      this.$confirm('是否确认操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 执行删除操作
          deleteContent(row.id).then(res => {
            // 刷新数据
            this.fetchData(this.node)
            // 弹出成功消息
            this.$message({
              type: 'success',
              message: '操作成功! '
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    // 当调整每页条数时触发
    handleSizeChange(val) {
      this.limit = val
      // console.log(`每页 ${val} 条`);
      // this.fetchData();
    },
    // 当切换页码时触发
    handleCurrentChange(val) {
      this.currentPage = val
      // this.fetchData();
      // console.log(`当前页: ${val}`);
    }
  }
}
</script>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.ContentimgSize {
  width: 50%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
